use crate::{
    error::Error,
    routers::route,
    util::{delete_file, generate_file},
};
use axum::{http::StatusCode, response::IntoResponse, routing::post, Extension, Json, Router};
pub fn code_router() -> Router {
    Router::new()
        .merge(code_admin_database_create_table())
        .merge(code_admin_database_drop_table())
}

// 创建数据库表的请求
fn code_admin_database_create_table() -> Router {
    async fn handler(Json(req): Json<serde_json::Value>) -> Result<impl IntoResponse, Error> {
        let j = req
            .as_object()
            .ok_or((StatusCode::BAD_REQUEST, "请求数据有错误"))?;

        let mut vec = Vec::new();
        let mut table_name = String::default();
        for (k, v) in j {
            if k.as_str() == "tablexxx" {
                table_name = v
                    .as_str()
                    .map(|s| s.to_string())
                    .ok_or(Error::from((StatusCode::BAD_REQUEST, "错误的类型")))?;
            } else {
                vec.push((
                    k.clone(),
                    v.as_str()
                        .map(|s| s.to_string())
                        .ok_or(Error::from((StatusCode::BAD_REQUEST, "错误的类型")))?,
                ));
            }
        }
        if table_name.is_empty() {
            return Err((StatusCode::BAD_REQUEST, "丢失表的名字").into());
        }

        generate_file(&table_name, vec).await?;
        Ok(format!("创建{}成功", table_name))
    }

    route("/admin/database/create/table", post(handler))
}

/// {"table_name": "name"}
fn code_admin_database_drop_table() -> Router {
    async fn handler(Json(req): Json<serde_json::Value>) -> Result<impl IntoResponse, Error> {
        let j = req
            .as_object()
            .ok_or(Error::from((StatusCode::BAD_REQUEST, "请求格式错误")))?;
        let table_name = j
            .get("table_name")
            .ok_or(Error::from((StatusCode::BAD_REQUEST, "table_name键丢失")))?;
        let table_name = table_name
            .as_str()
            .ok_or(Error::from((StatusCode::BAD_REQUEST, "值必须为字符串")))?;
        delete_file(table_name).await?;
        Ok(format!("删除{}成功", table_name))
    }

    route("/admin/database/drop/table", post(handler))
}
// {
//     "tablexxx_name": "post",
//     "name": "str",
//     "title": "f64",
//     "count": "u64",
//     "f1": "i64",
//     "f2": "f32",
//     "f3": "decimal(12, 2)",
//     "f4": "bool"
// }
